/*
 * Copyright (c) 2008 Anshuman Manur <anshuman.manur@gmail.com>,
 * Lavanya Shastri <lavanya.shastri@gmail.com>
 * 
 * This file is part of Andronova.
 * 
 * Andronova is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 * 
 * Andronova is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with Andronova.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * This file may use the functionality provided by the library
 * jid3lib version 0.5.4 (<http://sourceforge.net/projects/javamusictag/>).
 * jid3lib and its uses are covered by GNU Lesser General Public License.
 * 
 */

package com.googlecode.andronova;

import java.io.IOException;

import org.farng.mp3.AbstractMP3Tag;
import org.farng.mp3.id3.AbstractID3v2;
import org.farng.mp3.id3.ID3v2_3;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;

import com.googlecode.andronova.helper.DBConstants;
import com.googlecode.andronova.helper.Library;
import com.googlecode.andronova.helper.PlayList;
import com.googlecode.andronova.helper.Song;

public class TagEditor extends Activity {

	public static Song s;
	
	private Handler mHandler;
	private ProgressDialog pDialog;
	
	private Context ctx;
	
	private EditText title;
	private EditText album;
	private EditText artist;
	private AutoCompleteTextView genre;
	private EditText year;
	
	private String genreString;
	
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.tageditorscreen);
		setTitle("Tag Editor");
		
		if(s == null) 
			finish();
		
		ctx = this;
		mHandler = new Handler();
		
		title = (EditText) findViewById(R.id.te_title_et);
		album = (EditText) findViewById(R.id.te_album_et);
		artist = (EditText) findViewById(R.id.te_artist_et);
		genre = (AutoCompleteTextView) findViewById(R.id.te_genre_et);
		year = (EditText) findViewById(R.id.te_year_et);
		
		final AbstractID3v2 tag = s.getID3v2Tag();
		if(tag != null) {			
			title.setText(tag.getSongTitle());
			album.setText(tag.getAlbumTitle());
			artist.setText(tag.getLeadArtist());
			year.setText(tag.getYearReleased());
			genreString = tag.getSongGenre();
			
			if(genreString!=null && !genreString.equals("")) {
				if(genreString.startsWith("("))
					genreString = genreString.substring(1, genreString.length() - 1);
				if(Character.isDigit(genreString.charAt(0))) {
					int i = Integer.parseInt(genreString);
					genreString = Library.GENRE[i];
				}
			}
			genre.setText(genreString);
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.genre_list, Library.GENRE);
			genre.setAdapter(adapter);
		}
		else {
			this.showAlert(
					"Error", 
					android.R.id.appIcon, 
					"Cannot find ID3 tag in file\nApplication cannot create tags", 
					"OK",
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					},
					false,
					null);
			
		}
		
		ImageView okView = (ImageView) findViewById(R.id.te_save);
		ImageView cancelView = (ImageView) findViewById(R.id.te_cancel);
		
		okView.setImageResource(R.drawable.andro_ok);
		cancelView.setImageResource(R.drawable.andro_cancel);
		
		okView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				new Thread(new Runnable() {
					
					public void run() {
						final String message = "Updating ID3 tags";
						mHandler.post(new Runnable() {
							public void run() {
								pDialog = ProgressDialog.show(ctx, "Please Wait", message);
							}
						});
						
						try {
							String tit = title.getText().toString();
							String alb = album.getText().toString();
							String art = artist.getText().toString();
							String yea = year.getText().toString();
							
							String gen = genre.getText().toString();
							if(genreString!=null && !genreString.equals(gen)) 
								for(int i=0 ; i<Library.GENRE.length ; i++)
									if(gen.equals(Library.GENRE[i])) {
										gen = String.valueOf(i);
										gen = "(".concat(gen);
										gen = gen.concat(")");
										break;
									}
							AbstractMP3Tag tAG;
							if(tag != null)
								tAG = (AbstractMP3Tag) tag;
							else
								tAG = new ID3v2_3();
							tAG.setSongTitle(tit);
							tAG.setAlbumTitle(alb);
							tAG.setLeadArtist(art);
							tAG.setSongGenre(gen);
							tAG.setYearReleased(yea);
							s.setID3v2Tag(tAG);
							s.save();
												
							
							SQLiteDatabase db = openDatabase(DBConstants.DB_NAME, null);
							Library library = new Library(db);
							library.update(s);
							
							PlayList playlist = new PlayList(db);
							if(playlist.hasSong(s))
								playlist.update(s);
							pDialog.dismiss();
							setResult(RESULT_OK);
						}
						catch(final IOException e) {
							pDialog.dismiss();
							mHandler.post(new Runnable() {
								public void run() {
									showAlert(PlayScreen.ERROR, android.R.id.icon, "Unable to Write Tags to File" + "\n" + e.toString(), "OK", false);
								}
							});							
							setResult(RESULT_CANCELED);
						}
						catch(final Exception e) {
							pDialog.dismiss();
							mHandler.post(new Runnable() {
								public void run() {
									showAlert(PlayScreen.ERROR, android.R.id.icon, e.toString(), "OK", false);
								}
							});							
							setResult(RESULT_CANCELED);
						}
						finally {
							finish();
						}
					}
				}).start();
			}
		});
		
		cancelView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}	
}
